package top.codedance.iotp.converter.service.slave;

import top.codedance.iotp.converter.ConverterApplication;
import top.codedance.iotp.converter.bean.SlaveConnectParam;
import top.codedance.iotp.converter.service.slave.listenner.SerialPortListener;
import com.fazecast.jSerialComm.SerialPort;
import org.apache.log4j.Logger;

public class SerialSlave extends SerialAbstractAdapter {
    private static Logger logger = ConverterApplication.getLogger(SerialSlave.class);
    private SerialPort mSerialPort;

    public SerialSlave(SlaveConnectParam scp) {
        super(scp);
    }

    @Override
    public void init() {
        try {
            connect();
        }catch (Exception ex){
            logger.info(ex.getMessage());
            System.exit(0);
        }
        long time = System.currentTimeMillis();
        while (true) {
            if (mSerialPort == null || !mSerialPort.isOpen()) {
                try {
                    connect();
                }catch (Exception ex){
                    logger.info(ex.getMessage());
                }
                logger.info("Master is reconnect!");
            }else{
                if(System.currentTimeMillis() - time > 1000 * 3600 * 2){
                    destory();
                    try {
                        connect();
                    }catch (Exception ex){
                        logger.info(ex.getMessage());
                    }
                    time = System.currentTimeMillis();
                }
            }
            try {
                Thread.sleep(3000);
            } catch (Exception ex) { }
        }
    }

    @Override
    public void connect() {
        mSerialPort = SerialPort.getCommPort(param.getComName());
        mSerialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        mSerialPort.setComPortParameters(param.getBaudRate(), param.getDataBits(), param.getStopBits(), param.getParity());
        mSerialPort.addDataListener(new SerialPortListener(this));
        if (!mSerialPort.openPort(0, 512, 512)) {
            mSerialPort = null;
        }
        logger.info("Serial slave is running!");
    }

    @Override
    public boolean isOpen() {
        return mSerialPort.isOpen();
    }

    @Override
    public void destory() {
        if(mSerialPort != null && mSerialPort.isOpen()) {
            mSerialPort.closePort();
        }
    }

    @Override
    public synchronized void send(byte[] data) {
        if(mSerialPort == null || !mSerialPort.isOpen()) {
            connect();
        }
        if(mSerialPort != null && mSerialPort.isOpen()) {
            mSerialPort.writeBytes(data, data.length);
        }
    }
}
